<template>
  <div>
    <el-tooltip
      :content="$t('layout.cache.tooltip')"
      effect="dark"
      placement="bottom"
    >
      <svg-icon icon-class="clean" @click="handleCleanCache" />
    </el-tooltip>
  </div>
</template>

<script setup>
import { ref, h } from 'vue';
import {
  ElCheckboxGroup,
  ElCheckbox,
  ElMessageBox,
  ElMessage,
} from 'element-plus';
import ToolAPI from '@/api/admin/admin/tool';
import { useDictStoreHook, usePublicInfoStore } from '@/store';
import { i18nLoader } from '@/lang/i18nloader';
import { smartTranslate as $t } from '@/lang';

const { refreshDictionaryCache } = useDictStoreHook();
const { loadPublicInfo, clearPublicInfo } = usePublicInfoStore();

const cleanBrowserCache = async () => {
  clearPublicInfo();
  await refreshDictionaryCache();
  await i18nLoader.clearCache();
  await loadPublicInfo();
};

const handleCleanCache = async () => {
  const checked = ref([]);
  const checkboxOptions = [
    {
      label: $t('common.action.clear_browser_cache', '清除浏览器缓存'),
      value: 'localStorage',
    },
    {
      label: $t('common.action.clear_server_cache', '清除服务器缓存'),
      value: 'cache',
    },
    {
      label: $t('common.action.clear_runtime_log', '清除运行时日志'),
      value: 'runtime',
    },
    {
      label: $t('common.action.clear_admin_log', '清除系统日志'),
      value: 'log',
    },
  ];

  ElMessageBox.confirm('', {
    title: $t('common.message.placeholder.select_options', '请选择项目'),
    message: () => {
      return h(
        ElCheckboxGroup,
        {
          modelValue: checked.value,
          'onUpdate:modelValue': async (value) => {
            // 实现互斥选择逻辑
            if (value.includes('localStorage')) {
              // 如果选择了localStorage，检查是否是新选择
              if (!checked.value.includes('localStorage')) {
                try {
                  // 用户确认，只保留localStorage选项
                  checked.value = ['localStorage'];
                } catch {
                  // 用户取消，移除localStorage选项，保持其他选项
                  checked.value = value.filter(
                    (item) => item !== 'localStorage',
                  );
                }
              } else {
                // 如果localStorage已经选中，用户取消选择localStorage
                if (value.length < checked.value.length) {
                  checked.value = value.filter(
                    (item) => item !== 'localStorage',
                  );
                }
              }
            } else {
              // 没有选择localStorage，正常更新选择
              checked.value = value;
            }
          },
        },
        () =>
          checkboxOptions.map((option) => {
            // 计算是否应该禁用当前选项
            let isDisabled = false;
            if (option.value === 'localStorage') {
              // localStorage选项：当其他选项被选中时禁用
              isDisabled = checked.value.some(
                (item) => item !== 'localStorage',
              );
            } else {
              // 其他选项：当localStorage被选中时禁用
              isDisabled = checked.value.includes('localStorage');
            }

            return h(ElCheckbox, {
              label: option.label,
              value: option.value,
              disabled: isDisabled,
            });
          }),
      );
    },
    beforeClose: async (action, instance, done) => {
      if (action === 'confirm' && checked.value.length > 0) {
        try {
          let hasError = false;

          if (checked.value.includes('localStorage')) {
            // 清理浏览器缓存
            try {
              cleanBrowserCache();
            } catch (error) {
              hasError = true;
            }
          } else {
            // 清理其他缓存
            try {
              await ToolAPI.cleanCache({ cache_key: checked.value });
            } catch (error) {
              hasError = true;
            }
          }

          // 显示简化的清理结果
          if (hasError) {
            ElMessage.error($t('common.message.failed.clean', '清理失败'));
          } else {
            ElMessage.success($t('common.message.success.clean', '清理成功'));
          }

          done();
        } catch (error) {
          ElMessage.error($t('common.message.failed.clean', '清理失败'));
          done();
        }
      } else if (action === 'confirm' && checked.value.length === 0) {
        ElMessage.warning(
          $t('common.message.info.least one', '请至少选择一个项目'),
        );
        return false; // 阻止关闭对话框
      } else {
        done();
      }
    },
  });
};
</script>

<style lang="scss" scoped></style>
